<template>
  <div class="app-container">
    <template v-if="!showDetailIndex">
      <div class="search-container">
        <el-form ref="form" :model="queryParams" :inline="true">
          <el-form-item prop="sampleNumber" label="样本编号">
            <el-input v-model="queryParams.sampleNumber" placeholder="样本编号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item prop="status" label="样本状态">
            <el-select v-model="queryParams.status" placeholder="样本状态" @change="updateStatus">
              <!-- <el-option label="已创建" value="CREATE"></el-option> -->
              <el-option label="待寄出" value="TO_BE_SENT_OUT"></el-option>
              <el-option label="已寄出" value="SENT_OUT"></el-option>
              <el-option label="样本已收到" value="SAMPLE_RECEIVE"></el-option>
              <el-option label="实验室测序完成" value="REPORT_SEQ_END"></el-option>
              <el-option label="数据分析中" value="DATA_ANALYSIS"></el-option>
              <el-option label="样本审核中" value="REPORT_AUDIT"></el-option>
              <el-option label="完成" value="COMPLETED"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never">
        <template #header>
          <el-button type="success" @click="openDialog()"><i class="el-icon-circle-plus"></i> 新增</el-button>
          <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()"><i
              class="el-icon-delete"></i>删除</el-button>
        </template>
        <el-table v-loading="loading" :data="dataList" highlight-current-row border :cell-style="cellStyle"
          @cell-click="openDetail" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" width="55" prop="dataIndex" />
          <el-table-column label="样本编号" prop="number">
            <template slot-scope="scope">
              <el-tag size="medium">{{ scope.row.number }}</el-tag>
              <!-- <el-tag v-else type="info" size="medium">{{ scope.row.number }}</el-tag> -->
            </template>
          </el-table-column>
          <el-table-column label="用户" prop="fmtUserName" />
          <el-table-column label="手机号" prop="fmtUserPhone" />
          <el-table-column label="样本状态" prop="statusText" />
          <el-table-column label="更新时间" prop="updateTimeText" />
          <el-table-column fixed="right" label="操作" min-width="120" width="270">
            <template #default="scope">
              <!-- <el-button type="primary" size="small" link @click="openDetailProcess(scope.row)">查看</el-button> -->
              <el-button type="warning" size="small" link @click="openDialog(scope.row.id)">编辑</el-button>
              <el-button type="primary" size="small" link @click="openExpressDialog(scope.row)"
                v-if="scope.row.status == 'TO_BE_SENT_OUT'">呼叫快递</el-button>
              <el-button type="warning" size="small" link @click="cancelExpress(scope.row)"
                v-if="scope.row.status == 'SENT_OUT'">取消快递</el-button>
              <el-button type="primary" size="small" link @click="labSignDialog(scope.row)"
                v-if="scope.row.status == 'SENT_OUT'">实验室签收</el-button>
              <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)"
                v-if="isAdmin || scope.row.status == 'CREATE'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="block">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="10"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </el-card>

      <el-dialog :visible.sync="detailProcessDialog.visible" :title="detailProcessDialog.title" width="500px"
        :before-close="closeDetailProcessDialog">
        <div style="margin-bottom: 10px;">
          <p><span>样本编号：</span><span>{{ checkedSample.number }}</span></p>
          <p style="margin-top: 8px;"><span>样本状态：</span><span>{{ checkedSample.statusText }}</span></p>
        </div>
        <div style="height: 500px;">
          <el-steps direction="vertical" :active="activeStep">
            <el-step title="已创建" :description="sampleHistoryTimeMap['CREATE']"></el-step>
            <el-step title="待寄出" :description="sampleHistoryTimeMap['TO_BE_SENT_OUT']"></el-step>
            <el-step title="已寄出" :description="sampleHistoryTimeMap['SENT_OUT']"></el-step>
            <el-step title="样本已收到" :description="sampleHistoryTimeMap['SAMPLE_RECEIVE']"></el-step>
            <el-step title="测序完成" :description="sampleHistoryTimeMap['REPORT_SEQ_END']"></el-step>
            <el-step title="数据分析中" :description="sampleHistoryTimeMap['DATA_ANALYSIS']"></el-step>
            <el-step title="样本待审核" :description="sampleHistoryTimeMap['REPORT_AUDIT']"></el-step>
            <el-step title="已完成" :description="sampleHistoryTimeMap['COMPLETED']"></el-step>
          </el-steps>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="detailDialog.visible" :title="detailDialog.title" width="500px"
        :before-close="closeDetailDialog">
        <div>
          <p><span>样本编号：</span><span>{{ checkedSample.number }}</span></p>
          <p style="margin-top: 8px;"><span>样本状态：</span><span>{{ checkedSample.statusText }}</span></p>
          <p style="margin-top: 8px;"><span>更新时间：</span><span>{{ checkedSample.updateTimeText }}</span></p>
          <p style="margin-top: 8px;"><span>创建时间：</span><span>{{ checkedSample.createTimeText }}</span></p>
          <img :src="sampleImgUrl" style="margin-top: 10px; width: 320px;" />
        </div>
      </el-dialog>

      <!-- 样本表单弹窗 -->
      <el-dialog :visible.sync="dialog.visible" :title="dialog.title" width="500px" :before-close="closeDialog">
        <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="样本个数" prop="num" v-if="!formData.id">
            <el-input-number v-model="formData.num" controls-position="right" :min="1" :max="99"
              size="medium"></el-input-number>
          </el-form-item>
          <el-form-item label="绑定FMT供者" prop="saleUserId">
            <el-select v-model="formData.fmtUserId" placeholder="FMT供者信息">
              <el-option v-for="item in fmtDonorList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="addOrUpdate">确 定</el-button>
            <el-button @click="closeDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :visible.sync="notifyExpressSampleDialog.visible" title="呼叫快递" width="500px" :before-close="closeExpressDialog">
        <el-form ref="expressFormRef" :model="notifyExpressSampleFormData" :rules="rules" label-width="100px">
          <el-form-item label="是否虚拟寄件" prop="virtual">
            <el-radio v-model="notifyExpressSampleFormData.virtual" label="true">是</el-radio>
            <el-radio v-model="notifyExpressSampleFormData.virtual" label="false">否</el-radio>
          </el-form-item>
          <el-form-item label="寄件人姓名" prop="name">
            <el-input v-model="notifyExpressSampleFormData.name" placeholder="请输入用户姓名" />
          </el-form-item>
          <el-form-item label="寄件人电话" prop="phone">
            <el-input v-model="notifyExpressSampleFormData.phone" placeholder="请输入用户手机号" />
          </el-form-item>
          <el-form-item label="寄件地址" prop="addr">
            <el-cascader :options="options" v-model="selectedOptions" @change="changeExpressArea"></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="addrExt">
            <el-input v-model="notifyExpressSampleFormData.addr" type="textarea" :autosize="{ minRows: 4 }"
              placeholder="请输入详细地址" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="notifyExpress">绑 定</el-button>
            <el-button @click="closeExpressDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      
    </template>

    <sampleDetailDesign :checkedSample="checkedSample" v-if="showDetailIndex" @close="closeDetail"></sampleDetailDesign>

  </div>
</template>

<script>
import sampleDetailDesign from '@/views/aliyun/detection/sample/detail'
import fmtSampleApi from '@/api/aliyun/fmt/sample'
import expressApi from '@/api/aliyun/detection/express'
import fmtDonorApi from '@/api/aliyun/fmt/donor'
import { formatDate } from '@/utils/formatTime'
import { provinceAndCityData, regionData, codeToText } from 'element-china-area-data'

export default {
  name: 'sampleIndex',
  components: {
    sampleDetailDesign
  },
  data() {
    return {
      queryParams: {
        sampleNumber: '',
        pageNum: 0,
        pageSize: 10,
        status: '',
      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      userList: [],
      dialog: {},
      formData: {
        num: 1
      },
      rules: {},

      detailDialog: {},
      checkedSample: {},
      sampleImgUrl: '',

      statusMap: {
        CREATE: '已创建',
        TO_BE_SENT_OUT: '待寄出',
        SENT_OUT: '已寄出',
        SAMPLE_RECEIVE: '样本已收到',
        REPORT_SEQ_END: '实验室测序完成',
        DATA_ANALYSIS: '数据分析中',
        REPORT_AUDIT: '样本审核中',
        COMPLETED: '完成',
      },

      notifyExpressSampleDialog: {},
      notifyExpressSample: {},
      notifyExpressSampleFormData: {},

      expressBaseAddr: '',
      addrExtInfo: '',
      options: regionData,
      selectedOptions: [],

      viewFileVisible: false,
      inputFileData: [],
      outputFileData: [],
      viewFileSampleId: "",
      uploadAction: '',
      uploadFileVisible: false,
      headers: {},

      detailProcessDialog: {},
      activeStep: 0,
      sampleHistoryTimeMap: {},

      fmtDonorList: [],
      fmtDonorMap: {},
      surveyDialog: {},
      surveyObj: {},
      typeMap: {
        EXCLUSIVE_CHOICE: '单选',
        MULTIPLE_CHOICE: '多选',
        TEXTAREA: '填空',
      },
      answerFormData: [],
      optionTitleMap: {},
      answerId: null,
      showDetailIndex: false,

      isAdmin: false,
    };
  },
  mounted() {
    this.headers = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    };
    let userInfo = this.$store.state.userInfos.userInfos;
    let roleList = userInfo.roleList;
    if (roleList && roleList.length != 0) {
      roleList.forEach(v => {
        if (v.enName == "ADMIN") {
          this.isAdmin = true;
          return;
        }
      })
    }
  },
  methods: {
    closeDetail() {
      this.showDetailIndex = false;
    },
    updateStatus() {
      this.handleQuery();
    },
    openDetailProcess(row) {
      this.checkedSample = row;
      this.showDetailIndex = true;

    },
    closeDetailProcessDialog() {
      this.$set(this.detailProcessDialog, 'visible', false);
    },
    // 查看文件
    viewFile(id) {
      this.viewFileSampleId = id;
      this.viewFileVisible = true;
      sampleApi.getFileList(this.viewFileSampleId).then(res => {
        let fileData = res.data;
        let outOutData = [];
        let inputData = [];
        fileData.forEach((i) => {
          if (i.fileType == "OUTPUT") {
            outOutData.push(i)
          }
          if (i.fileType == "INPUT") {
            inputData.push(i);
          }
        })
        this.outputFileData = outOutData;
        this.inputFileData = inputData;
      })
    },
    unloadInputFlie() {
      this.uploadFileVisible = true;
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    uploadFileSuccess() {
      this.uploadFileVisible = false;
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.handleQuery();
    },
    openDetail(row, column) {
      if (column.property == "number") {
        this.$set(this.detailDialog, 'visible', true);
        this.$set(this.detailDialog, 'title', '样本详情');
        this.checkedSample = row;
        fmtSampleApi.geneBarCode(row.number).then(res => {
          this.sampleImgUrl = window.URL.createObjectURL(res);
        })
      }
    },
    labSignDialog(row) {
      fmtSampleApi.signSample(row.number).then((res) => {
        this.$message({ message: '样本签收成功！', type: 'success' });
        this.handleQuery();
      });
    },
    cancelExpress(row) {
      expressApi.cancel(row.id).then(res => {
        this.$message({ message: '样本快递已取消成功！', type: 'success' });
        this.handleQuery();
      })
    },
    notifyExpress() {
      let params = {
        fmtSampleId: this.notifyExpressSample.id,
        name: this.notifyExpressSampleFormData.name,
        phone: this.notifyExpressSampleFormData.phone,
        addr: this.expressBaseAddr + this.notifyExpressSampleFormData.addr,
        addrExtInfo: JSON.stringify(this.addrExtInfo),
        virtual: this.notifyExpressSampleFormData.virtual,
      };
      expressApi.addFmtSample(params).then(res => {
        this.$message({ message: 'FMT 样本呼叫快递成功！', type: 'success' });
        this.$set(this.notifyExpressSampleDialog, 'visible', false);
        this.handleQuery();
      })
    },
    changeExpressArea(vals) {
      this.expressBaseAddr = codeToText[vals[0]] + codeToText[vals[1]] + codeToText[vals[2]];
      this.addrExtInfo = vals;
    },
    openExpressDialog(row) {
      this.notifyExpressSample = row;
      this.$set(this.notifyExpressSampleDialog, 'visible', true);
    },
    closeExpressDialog() {
      this.$set(this.notifyExpressSampleDialog, 'visible', false);
    },
    handleQuery() {
      this.loading = true;
      console.log(this.queryParams.status)
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        statuses: (this.queryParams.status == null || this.queryParams.status == '') ? [] : [this.queryParams.status],
        sampleNumber: this.queryParams.sampleNumber,
      };
      fmtSampleApi.page(params).then((res) => {
        let data = res.data;
        let index = 1
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.statusText = this.statusMap[v.status];
          v.dataIndex = index++;
        });
        this.dataList = data.content;

        this.total = data.count;
        this.loading = false;
      }).catch(() => { });
    },
    resetQuery() {
      this.queryParams = {
        sampleNumber: '',
        pageNum: 0,
        pageSize: 10,
        status: '',
      };
      this.handleQuery();
    },
    addOrUpdate() {
      if (!this.formData.fmtUserId) {
        this.$message.error('未选择FMT供者，不可添加FMT样本！');
        return;
      }
      let that = this;
      if (this.formData.id) {
        fmtSampleApi.update({
          id: this.formData.id,
          fmtUserId: this.formData.fmtUserId,
          // saleUserName: this.fmtDonorMap[this.formData.saleUserId],
        }).then((res) => {
          this.$message({ message: 'FMT 样本更新成功！', type: 'success' });
          that.closeDialog();
        });
      } else {
        fmtSampleApi.add({
          fmtUserId: this.formData.fmtUserId,
          // saleUserName: this.fmtDonorMap[this.formData.fmtUserId],
          num: this.formData.num,
        }).then((res) => {
          this.$message({ message: 'FMT 样本添加成功！', type: 'success' });
          this.closeDialog();
        });
      }
    },
    openDialog(id) {
      let that = this;
      that.fmtDonorList = [];
      fmtDonorApi.list().then(res => {
        res.data.forEach(v1 => {
          v1.id = v1.id + '';
          that.fmtDonorMap[v1.id] = v1.name;
          that.fmtDonorList.push(v1)
        })
        this.$set(this.dialog, 'visible', true);

        if (id) {
          this.$set(this.dialog, 'title', '编辑FMT 样本');
          fmtDonorApi.get(id).then((res) => {
            let data = res.data;
            that.formData = data;
          });
        } else {
          this.$set(this.dialog, 'title', '新增FMT 样本');
          that.formData = {
            num: 1
          };
        }
      })
    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    // 删除样本
    handleDelete(id) {
      this.$confirm("确定删除该数据, 是否继续?", "提示", {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        if (id) {
          fmtSampleApi.delete(id).then((res) => {
            this.$message.success('FMT 样本删除成功！');
            this.handleQuery();
          });
        } else {
          this.$message.error('暂不支持批量删除FMT 样本！');
        }
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },
    closeDetailDialog() {
      this.$set(this.detailDialog, 'visible', false);
      this.$set(this.detailDialog, 'title', '');
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property == "number") {
        return {
          "cursor": "pointer"
        }
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}

.viewFileVisible_box {
  display: flex;
}

.input_file {
  width: 50%;
  border: 1px solid #DCDFE6;
  padding: 2% 1%;
  margin-right: 2%;
}

.input_file h3 {
  /* margin-bottom: 2%; */
}

.output_file {
  width: 50%;
  border: 1px solid #DCDFE6;
  padding: 2%;
}

.output_file h3 {
  /* margin-bottom: 2%; */
}

.input_file_top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2%;
}
</style>